package com.dragon.lib_mvi.base

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment

/***
 * @ClassName BaseLazyLoadFragment
 * @Author Administrator
 * @description 懒加载Fragment:页面创建时，不会加载数据，只有当页面显示时，才会加载数据。
 * @date 2025/2/24
 */
abstract class BaseLazyLoadFragment : Fragment() {
    /**
     * 是否初始化过
     */
    protected var isInit = false

    /**
     * 是否已经完成加载
     */
    protected var isLoaded = false

    protected lateinit var mView: View

    /**
     * 创建view
     */
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        mView = getFragmentRootView(inflater, container, savedInstanceState)
        isInit = true
        prepareLoadData()
        initView()
        return mView
    }

    /**
     * view被创建好了
     */
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        initEnv()
        initEvent()
        initData()
    }

    /**
     * 销毁view
     */
    override fun onDestroyView() {
        super.onDestroyView()
        isInit = false
        isLoaded = false
    }

    private fun prepareLoadData() {
        if (!isInit) return
        if (userVisibleHint) { //可见
            lazyLoad()
            isLoaded = true
        } else {
            if (isLoaded) {
                stopLoad()
            }
        }
    }

    /**
     * 延时加载
     */
    abstract fun lazyLoad()

    /**
     * 停止加载可以用于释放资源
     */
    protected fun stopLoad() {}


    protected open fun initEnv() {}
    protected open fun initEvent() {}

    protected open fun initData() {}

    protected open fun initView() {}

    /**
     * 获得fragment视图
     */
    abstract fun getFragmentRootView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View


    /**
     * 查找并获取资源
     */
    protected fun <T : View> findViewById(id: Int): T {
        return mView.findViewById(id)
    }


    /**
     * 显示提示消息
     */
    protected fun showMsg(msg: String?) {
        if (activity is BaseActivity) {
            (activity as BaseActivity).showMsg(msg ?: "")
        }

    }


}